<?php
//-----------------------------------------------------------
// Php2Python(PHP and Python).
//   (2012-15 http://code.google.com/p/ppython/)
//
// License: http://www.apache.org/licenses/LICENSE-2.0
//-----------------------------------------------------------

define("LAJP_IP", "127.0.0.1"); //Python端IP
define("LAJP_PORT", 21230); //Python端侦听端口

define("PARAM_TYPE_ERROR", 101); //参数类型错误
define("SOCKET_ERROR", 102); //SOCKET错误
define("LAJP_EXCEPTION", 104); //Python端反馈异常

function php2python($arg_array) {

	if (!is_string($arg_array['m'])) {
		throw new Exception("[Php2Python Error] lapp_call function's first argument must be string \"module_name::function_name\".", PARAM_TYPE_ERROR);
	}

	if (($socket = socket_create(AF_INET, SOCK_STREAM, 0)) === false) {
		throw new Exception("[Php2Python Error] socket create error.", SOCKET_ERROR);
	}

	if (socket_connect($socket, LAJP_IP, LAJP_PORT) === false) {
		throw new Exception("[Php2Python Error] socket connect error.", SOCKET_ERROR);
	}

	//消息体序列化
	$request = json_encode($arg_array);
	$req_len = strlen($request);

	$request = $req_len . "," . $request;

	$send_len = 0;
	do {
		//发送
		if (($sends = socket_write($socket, $request, strlen($request))) === false) {
			throw new Exception("[Php2Python Error] socket write error.", SOCKET_ERROR);
		}

		$send_len += $sends;
		$request = substr($request, $sends);

	} while ($send_len < $req_len);

	//接收
	$response = "";
	while (true) {
		$recv = "";
		if (($recv = socket_read($socket, 1400)) === false) {
			throw new Exception("[Php2Python Error] socket read error.", SOCKET_ERROR);
		}
		if ($recv == "") {
			break;
		}

		$response .= $recv;

		//echo "{$response}<br>";

	}

	//关闭
	socket_close($socket);

	if (empty($response)) {
		throw new Exception("[Php2Python Error] socket response error.", $response);
	}

    //返回结果
    return json_decode($response);
}
?>